<template>
  <!-- v-loading="true" -->
  <div>
    <el-card shadow="never">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-select style="width: 100%" v-model="serachForm.productclassoneid" placeholder="请选择一级分类"
            @change="selectChange">
            <el-option v-for="option in searchList" :key="option.px" :label="option.name" :value="option.id" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select style="width: 100%" v-model="serachForm.productclasstwoid" placeholder="请选择二级分类"
            @change="selectChangeTwo">
            <el-option v-for="option in productclasstwoList" :key="option.px" :label="option.name" :value="option.id" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-input v-model="serachForm.name" placeholder="请输入产品名字" />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="onSubmit">搜索</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- <pageSearch :searchFormConfig="searchFormConfigRef" @searchSubmit="searchSubmit" /> -->
    <pageTable :tableData="tableData" :tableInit="params.tableInit" @sizeChange="sizeChange"
      @currentChange="currentChange" @exportFn="exportExcel" v-loading="loading" @pageAdd="openDialogFn('新增')">

      <template #status="{ row }">
        {{ filterStatus(row.status) }}
      </template>
      <template #list="{ row }">
        <div>
          <div class="flex justify-center">
            <div class="w-[120px]">{{ row.levelone }}件以下价格</div> {{ row.underlevelone }}
          </div>

          <div class="flex justify-center">
            <div class="w-[120px]">{{ row.levelone }}-{{ row.leveltwo }}件价格</div> {{ row.underlevetwo }}
          </div>
          <div class="flex justify-center">
            <div class="w-[120px]">{{ row.leveltwo }}-{{ row.levelthree }}件价格</div> {{ row.underlevethree }}
          </div>
          <div class="flex justify-center">
            <div class="w-[120px]">{{ row.levelthree }}件以上价格</div> {{ row.abovelevethree }}
          </div>
        </div>
      </template>
      <template #isshiyong="{ row }">
        {{ row.isshiyong == 0 ? '提供' : '不提供' }}
      </template>
      <template #operation="{ row }">
        <el-button type="primary" link @click="openDialogFn('编辑', row)">编辑</el-button>
        <el-popconfirm title="确认要删除吗?" @confirm="delData(row.id)">
          <template #reference>
            <el-button type="danger" link>删除</el-button>
          </template>
        </el-popconfirm>
      </template>



    </pageTable>

    <Dialog width="30%" top="20vh" ref="DialogRef" :title="typeText" @submit="submitForm(ruleFormRef)"
      @onclose="resetForm(ruleFormRef)">
      <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品分类">
              <el-cascader v-model="ruleForm.pOPtionsIDList" class="w-full mb-[10px]" :options="searchList" :props="{
        label: 'name',
        value: 'id',
        children: 'list'
      }" @change="handleChange" :teleported="false" placeholder="请选择一二级菜单" />
            </el-form-item>
          </el-col>



          <el-col :span="12">
            <el-form-item label="产品名称" prop="productid">
              <el-select v-model="ruleForm.productid" :teleported="false" placeholder="请选择产品" style="width: 100%"
                @change="handleChange1">
                <el-option v-for="item in productList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>







          <el-col :span="12">
            <el-form-item label="供货状态" prop="status">
              <el-select style="width: 100%" v-model="ruleForm.status" placeholder="请选择">
                <el-option v-for="option in productStatus" :key="option.id" :label="option.name" :value="option.id" />
              </el-select>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="质量等级" prop="level">
              <el-input v-model="ruleForm.level" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>



          <el-col :span="12">
            <el-form-item label="库存" prop="inventory">
              <el-input v-model="ruleForm.inventory" placeholder="请输入" type="number"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="产品定价" prop="underlevelone">
              <el-row class="w-full">
                <el-col :span="24">
                  <el-row :gutter="20">
                    <el-col :span="7">
                      <el-input placeholder="0" disabled />
                    </el-col>
                    <el-col :span="4">
                      <el-tooltip class="box-item" effect="dark" content="包含最多数量" placement="top-start">
                        <div class="flex justify-center">
                          {{ '至(<)' }} </div>
                      </el-tooltip>
                    </el-col>
                    <el-col :span="7">
                      <el-input v-model="ruleForm.levelone" placeholder="最多数量" />
                    </el-col>
                    <el-col :span="6">
                      <el-input v-model="ruleForm.underlevelone" placeholder="请输入单价" />
                    </el-col>
                  </el-row>
                </el-col>
                <!-- <el-col :span="24" class="mt-4">
                  <el-button>添加定价</el-button>
                </el-col> -->
              </el-row>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item prop="underlevetwo">
              <el-row class="w-full  mt-[10px]">
                <el-col :span="24">


                  <el-row :gutter="20">
                    <el-col :span="7">
                      <el-input v-model="ruleForm.levelone" placeholder="最少数量" />
                    </el-col>
                    <el-col :span="4">
                      <el-tooltip class="box-item" effect="dark" content="包含最多数量" placement="top-start">
                        <div class="flex justify-center">
                          {{ '至(<)' }} </div>
                      </el-tooltip>
                    </el-col>
                    <el-col :span="7">
                      <el-input v-model="ruleForm.leveltwo" placeholder="最多数量" />
                    </el-col>
                    <el-col :span="6">
                      <el-input v-model="ruleForm.underlevetwo" placeholder="请输入单价" />
                    </el-col>
                  </el-row>
                </el-col>
                <!-- <el-col :span="24" class="mt-4">
                  <el-button>添加定价</el-button>
                </el-col> -->
              </el-row>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item prop="underlevethree">
              <el-row class="w-full  mt-[10px]">
                <el-col :span="24">


                  <el-row :gutter="20">
                    <el-col :span="7">
                      <el-input v-model="ruleForm.leveltwo" placeholder="最少数量" />
                    </el-col>
                    <el-col :span="4">

                      <el-tooltip class="box-item" effect="dark" content="包含最多数量" placement="top-start">
                        <div class="flex justify-center">
                          {{ '至(<)' }} </div>
                      </el-tooltip>

                    </el-col>
                    <el-col :span="7">
                      <el-input v-model="ruleForm.levelthree" placeholder="最多数量" />
                    </el-col>
                    <el-col :span="6">
                      <el-input v-model="ruleForm.underlevethree" placeholder="请输入单价" />
                    </el-col>
                  </el-row>
                </el-col>
                <!-- <el-col :span="24" class="mt-4">
                  <el-button>添加定价</el-button>
                </el-col> -->
              </el-row>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item prop="abovelevethree">
              <el-row class="w-full mt-[10px]">
                <el-col :span="24">


                  <el-row :gutter="20">
                    <el-col :span="8">
                      <el-input v-model="ruleForm.levelthree" placeholder="最少数量" />
                    </el-col>
                    <el-col :span="2">
                      <div class="flex justify-center">
                        至
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <el-input disabled placeholder="更多" />
                    </el-col>
                    <el-col :span="6">
                      <el-input v-model="ruleForm.abovelevethree" placeholder="请输入单价" />
                    </el-col>
                  </el-row>
                </el-col>


                <!-- <el-col :span="24" class="mt-4">
                  <el-button>添加定价</el-button>
                </el-col> -->
              </el-row>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="产品封装" prop="packagepr">
              <el-input v-model="ruleForm.packagepr" autocomplete="off" placeholder="请输入产品封装" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="MSL等级" prop="msl">
              <el-input v-model="ruleForm.msl" autocomplete="off" placeholder="请输入MSL等级" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="提供样品">
              <el-radio-group v-model="ruleForm.isshiyong">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="是否上架">
              <el-switch :active-value="1" :inactive-value="0" v-model="ruleForm.sxjtype" class="mb-2" />
            </el-form-item>
          </el-col>




        </el-row>
      </el-form>
    </Dialog>



  </div>
</template>

<script setup lang="ts">
import pageTable from "@/components/base-ui/page-table";
import Dialog from "@/components/base-ui/dialog";
import { reactive, ref, computed } from 'vue'
import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { clone, debounce } from "@pureadmin/utils";
import { randomNumber } from '@/utils/xwCommon'
import { tableInit } from "./config/table.config";
import { usepageTable } from '@/components/base-ui/page-table/usePageTable'
import { shoppingmallselpage, shoppingmallinsershop, shoppingmallupdateshop, shoppingmalldelshoppingmall } from '@/api/shop'
import { getselpage } from '@/api/classification'
import { productselpage } from '@/api/productList'
import { message } from "@/utils/message";

// 搜索


// 搜索
const serachForm = reactive({
  name: '',
  productclassone: '',  //一级产品类名称
  productclassoneid: '',  //一级产品类id（大类）
  productclasstwo: '',  //二级产品类名称（下级）
  productclasstwoid: '',  //二级产品类id（下级）
})
// 获取搜索下拉数据
const searchList = ref([])

const getSearchData = () => {
  getselpage().then(res => {
    searchList.value = res.result
  })
}

getSearchData()

const selectChange = (e) => {
  const item = searchList.value.find(v => v.id === e)
  if (item) {
    serachForm.productclassone = item.name
    serachForm.productclassoneid = e
    serachForm.productclasstwo = ''
    serachForm.productclasstwoid = ''
  }
}



const selectChangeTwo = (e) => {
  const item = productclasstwoList.value.find(v => v.id === e)
  if (item) {
    serachForm.productclasstwo = item.name
    serachForm.productclasstwoid = e
  }
}


const onSubmit = () => {
  serachVal.value = serachForm
  getData()
}

const handleChange = (value) => {
  searchList.value.forEach(v => {
    if (v.id === value[0]) {
      ruleForm.productclassone = v.name
      ruleForm.productclassoneid = value[0]
    }
    v.list.forEach(i => {
      if (i.id === value[1]) {
        ruleForm.productclasstwo = i.name
        ruleForm.productclasstwoid = value[1]
      }
    })
  })
  getproductList()
  ruleForm.productid = ''
  ruleForm.name = ''
}


const handleChange1 = (value) => {
  let item = productList.value.find(v => v.id === value)
  if (item) {
    ruleForm.name = item.name
  }
}


const productList = ref([])
const productLoading = ref(false)
const getproductList = () => {
  productLoading.value = true
  productList.value = []
  let Q = {
    index: 1,
    size: 1000,
    name: '',
    productclassone: ruleForm.productclassone,
    productclassoneid: ruleForm.productclassoneid,
    productclasstwo: ruleForm.productclasstwo,
    productclasstwoid: ruleForm.productclasstwoid,
  }
  productselpage(Q).then(res => {
    res.result.forEach(v => {
      v.productid = v.id
    })

    productList.value = res.result
  }).finally(() => {
    productLoading.value = false
  })
}








const productclasstwoList = computed(v => {
  let item = searchList.value.find(v => serachForm.productclassoneid == v.id)
  if (item) {
    return item?.list
  } else {
    return []
  }
})



// 表格

const {
  exportExcel,
  tableData,
  getData,
  params,
  loading,
  sizeChange,
  currentChange,
  delData,
  filterStatus,
  DialogRef,
  serachVal,
  openDialog,
  productStatus
} = usepageTable({
  tableInit,
  getRes: shoppingmallselpage,
  delRes: shoppingmalldelshoppingmall,
  otherQuery: {
    ptype: 0
  }
})

getData()






const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  productclassone: '',
  productclassoneid: '',
  productclasstwo: '',
  productclasstwoid: '',
  productid: '',
  pOPtionsIDList: [],
  status: '',
  level: '', //质量等级
  inventory: 0, // 库存

  // 价格
  underlevelone: '',
  underlevetwo: '',
  underlevethree: '',
  abovelevethree: '',
  // 数量
  levelone: '',
  leveltwo: '',
  levelthree: '',

  packagepr: '', //包装
  msl: '',  //MSL等级
  sxjtype: 1, //商城上下架状态 0 未上架 1 上架
  isshiyong: 1,//是否开放申请试用 0开放 1不开放	
  id: '',
  name: '',// 产品名称
})



const checkValue1 = (rule: any, value: any, callback: any) => {
  if (!ruleForm.levelone || !ruleForm.underlevelone) {
    return callback(new Error('请正确填写数量与价格'))
  } else {
    callback()
  }
}
const checkValue2 = (rule: any, value: any, callback: any) => {
  if (!ruleForm.leveltwo || !ruleForm.underlevetwo) {
    return callback(new Error('请正确填写数量与价格'))
  } else {
    callback()
  }
}
const checkValue3 = (rule: any, value: any, callback: any) => {
  if (!ruleForm.levelthree || !ruleForm.underlevethree) {
    return callback(new Error('请正确填写数量与价格'))
  } else {
    callback()
  }
}
const checkValue4 = (rule: any, value: any, callback: any) => {
  if (!ruleForm.abovelevethree) {
    return callback(new Error('请正确填写数量与价格'))
  } else {
    callback()
  }
}


const rules = reactive<FormRules<typeof ruleForm>>({
  productid: [
    { required: true, message: '请选择产品', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择供货状态', trigger: 'blur' },
  ],
  level: [{ required: true, message: '请填写质量等级', trigger: 'blur' }],
  inventory: [{ required: true, message: '请填写库存', trigger: 'blur' }],
  packagepr: [{ required: true, message: '请填写包装', trigger: 'blur' }],
  msl: [{ required: true, message: '请填写MSL等级', trigger: 'blur' }],
  underlevelone: [{ validator: checkValue1, trigger: 'blur' }],
  underlevetwo: [{ validator: checkValue2, trigger: 'blur' }],
  underlevethree: [{ validator: checkValue3, trigger: 'blur' }],
  abovelevethree: [{ validator: checkValue4, trigger: 'blur' }],
})



const typeText = ref('')
const openDialogFn = (text, row) => {
  typeText.value = text
  if (row) {
    const temporary = clone(row, true);
    Object.keys(ruleForm).forEach((key) => ruleForm[key] = temporary[key])
    ruleForm.pOPtionsIDList = [
      temporary.productclassoneid,
      temporary.productclasstwoid,
    ]
    getproductList()

  }
  openDialog()
}


const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      let fn = typeText.value == '新增' ? shoppingmallinsershop : shoppingmallupdateshop
      fn(ruleForm).then(() => {
        message(`${typeText.value}成功`, {
          type: "success"
        });
        DialogRef.value.close()
        getData()

      })

    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()

  ruleForm.productclassone = '',
    ruleForm.productclassoneid = '',
    ruleForm.productclasstwo = '',
    ruleForm.productclasstwoid = '',
    ruleForm.productid = '',
    ruleForm.pOPtionsIDList = [],
    ruleForm.status = '',
    ruleForm.level = '', //质量等级
    ruleForm.inventory = 0, // 库存

    // 价格
    ruleForm.underlevelone = '',
    ruleForm.underlevetwo = '',
    ruleForm.underlevethree = '',
    ruleForm.abovelevethree = '',
    // 数量
    ruleForm.levelone = '',
    ruleForm.leveltwo = '',
    ruleForm.levelthree = '',

    ruleForm.packagepr = '', //包装
    ruleForm.msl = '',  //MSL等级
    ruleForm.sxjtype = 1, //商城上下架状态 0 未上架 1 上架
    ruleForm.isshiyong = 1,//是否开放申请试用 0开放 1不开放	
    ruleForm.id = '',
    ruleForm.name = ''

}
</script>

<style scoped>
:deep(.el-form-item__label) {
  font-weight: 600;
}
</style>
